package com.boomcat.boomcat.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.boomcat.boomcat.domain.Order;
import com.boomcat.boomcat.dto.OrderDto;
import com.boomcat.boomcat.result.Result;
import com.boomcat.boomcat.service.OrderService;
import com.boomcat.boomcat.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/order")
@CrossOrigin(origins = "*")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/add")
    Result add(@RequestBody JSONObject jsonObject) {
        System.out.println("order add");

        String token = (String) jsonObject.get("token");
        Long userId = JwtUtil.getUserId(token);
        Long expertId = Long.valueOf((String) jsonObject.get("expertId"));
        String expertName = (String) jsonObject.get("expertName");

        String date = (String) jsonObject.get("date");

        String[] t = date.split("T");

        String d = t[0] + " " + t[1].substring(0, 8);


        String createdDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        Order order=new Order();
        order.setUserId(userId);
        order.setExpertId(expertId);
        order.setDate(d);
        order.setExpertName(expertName);
        order.setCreatedDate(createdDate);
        orderService.insert(order);
        return Result.success();
    }

    @PostMapping("/select")
    Result select(@RequestBody JSONObject jsonObject) {
        System.out.println("order select");

        String token = (String) jsonObject.get("token");

        System.out.println("token is "+token);

        Long userId = JwtUtil.getUserId(token);

        System.out.println("userid is "+userId);

        List<Order>orders=orderService.select(userId);
        List<OrderDto> orderDtos = orders.stream().map(OrderDto::new).toList();

        JSONArray jsonArray = new JSONArray();
        jsonArray.addAll(orderDtos);

        System.out.println(jsonArray);

        return Result.success(jsonArray);

    }


}
